#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/10/15 8:36
# @Author  : zy
# @File    : file_upload.py
from pathlib import Path
import streamlit as st
import os, time

# 设置页面标题
st.title('文件示例_上传')


def upload_0():
    # 文件上传
    uploaded_file = st.file_uploader("请选择文件进行上传", type=None)

    # 检查是否有文件上传
    if uploaded_file is not None:
        # 显示文件信息
        st.write(f"文件名: {uploaded_file.name}")
        st.write(f"文件大小: {uploaded_file.size} 字节")

        # 获取文件字节内容
        file_bytes = uploaded_file.read()

        # 将文件保存到本地
        save_path = f"./{uploaded_file.name}"
        with open(save_path, "wb") as f:
            f.write(file_bytes)

        st.success(f"文件已保存到: {save_path}")


def upload_1():
    # 标题
    st.markdown(
        """
        <h2 style='text-align: center; color: #FF6347;'>文件上传与保存</h2>
        """,
        unsafe_allow_html=True
    )

    # 文件上传
    uploaded_file = st.file_uploader("请上传文件", type=None)

    # 检查是否有文件上传
    if uploaded_file is not None:
        # 显示文件信息
        st.markdown(f"**文件名：** {uploaded_file.name}")
        st.markdown(f"**文件大小：** {uploaded_file.size / (1024 * 1024):.2f} MB")

        # 设定保存路径
        save_path = f"./{uploaded_file.name}"

        # 显示进度条
        progress_bar = st.progress(0)

        # 初始化
        bytes_written = 0  # 已写入的字节数

        # 打开文件并分块写入本地文件
        with open(save_path, "wb") as f:
            while True:
                # 建立文件块：从上传的文件中按块读取数据
                file_chunk = uploaded_file.read(1024 * 1024)

                if not file_chunk:
                    break  # 读取完成

                # 将文件块写入到本地文件
                f.write(file_chunk)

                # 字节数递增
                bytes_written += len(file_chunk)

                # 更新进度条
                progress_percent = bytes_written / uploaded_file.size
                progress_bar.progress(progress_percent)

        st.success(f"文件已保存到: {save_path}")
        st.markdown(f"**总写入字节数：** {bytes_written}")








if __name__ == "__main__":
    upload_1()


